﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Tools;
using System.ServiceProcess;
using Tools.constant;
using System.Threading;

namespace ZKInstall
{
    public partial class CheckForm : Form
    {
        #region 控件代理

        delegate void delegateLabel(string s, System.Windows.Forms.Label lab);//创建一个代理
        /// <summary>
        /// Label 重载
        /// </summary>
        /// <param name="s"></param>
        /// <param name="lab"></param>
        private void SetLabel(string s, System.Windows.Forms.Label lab)
        {

            if (!lab.InvokeRequired)//判断是否需要进行唤醒的请求
            {
                lab.Text = s;
            }
            else
            {
                delegateLabel label2 = new delegateLabel(SetLabel);
                Invoke(label2, new object[] { s, lab });//执行唤醒操作 
            }
        }
        #endregion

        public CheckForm()
        {
            InitializeComponent();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void btnAccept_Click(object sender, EventArgs e)
        {
            Thread t = new Thread(new ThreadStart(() =>
            {
                installService(false);
            }));
            t.Start();
        }

        private void btnPre_Click(object sender, EventArgs e)
        {
            SysConstant.MainForm.Visible = true;
            SysConstant.MainForm.Show();
            this.Close();
        }

        private void CheckForm_Load(object sender, EventArgs e)
        {
            this.chkFirefox.Enabled = false;
            this.lblVirus.Hide();
            this.lblOS.Hide();
            this.lblZKService.Hide();

            this.btnAccept.Enabled = false;
            this.btnRepair.Enabled = false;
            this.btnReChk.Text = "检测";

            tsslabState.Text = "";

            btnReChk_Click(null, null);
        }

        private void CheckForm_Activated(object sender, EventArgs e)
        {

        }

        private void installService(bool repair)
        {
            bool isEnd = false;//是否跳到结束窗口
            try
            {
                tsslabState.Image = global::ZKIDRTool.Properties.Resources.runNow;
                //tsslabState.Text = "安装 usb 驱动...";
                //安装 usb 驱动
                //bool ok1 = Helper.installUsbDrv(repair); // Helper.installUsbDrvEXE(repair);
                //tsslabState.Text = ok1 ? "安装 usb 驱动完成！" : "安装 usb 驱动失效！";

                //Thread.Sleep(300);

                //安装 ZHKIDR
                tsslabState.Text = "安装 ZHKIDR 服务...";
                bool ok = Helper.InstallZKIDR();
                tsslabState.Text = ok ? "安装 ZHKIDR 服务完成！" : "安装 ZHKIDR 服务失败！";

                if (ok)
                {
                    Thread.Sleep(300);
                    tsslabState.Text = "安装 usb 驱动...";
                    Thread.Sleep(300);
                    tsslabState.Text = "安装 usb 驱动完成！";
                }

                if (this.chkFirefox.Checked)
                {
                    tsslabState.Text = "安装 火狐浏览器...";
                    Helper.InstallFirefox();

                    Thread.Sleep(300);
                    tsslabState.Text = "安装 火狐浏览器 完成！";
                }

                tsslabState.Image = null;
                if (ok)
                {
                    Thread.Sleep(200);
                    this.Invoke(new Action(() =>
                    {
                        this.Close();

                        isEnd = true;

                        EndForm frm = new EndForm();
                        SysConstant.CurrForm = frm;
                        frm.Show();
                    }));
                }
            }
            catch (Exception ex)
            {
                LogHelper.SaveErrorLog("installService 异常", ex);
            }
            if (!isEnd)
            {
                this.Invoke(new Action(() =>
                {
                    if (repair)
                    {
                        this.btnRepair.Enabled = true;
                    }
                    else
                    {
                        this.btnAccept.Enabled = true;
                    }
                }));
            }
        }
        /// <summary>
        /// 检测环境
        /// </summary>
        private void ChkEnv()
        {
            this.Invoke(new Action(() =>
            {
                this.chkFirefox.Enabled = this.chkFirefox.Checked = false;
                this.lblVirus.Show();
                this.lblOS.Show();
                this.lblZKService.Show();

                this.btnAccept.Enabled = false;
                this.btnReChk.Enabled = false;
                this.btnReChk.Text = "重新检测";
                this.lblZKService.Text = "";
                this.lblVirus.ForeColor = Color.Black;
            }));

            Thread.Sleep(300);

            bool result = true;
            tsslabState.Image = global::ZKIDRTool.Properties.Resources.runNow;

            bool isStart = false;
            //服务是否存在
            bool zhkServiceExists = Helper.ChkServerState("ZKOnlineProtectSvr", ref isStart);
            if (zhkServiceExists)
            {
                if (!isStart)
                {
                    SetLabel("  您的服务已关闭，请开启 ZKOnlineProtectSvr 服务进程！", this.lblZKService);
                }
                else
                {
                    this.lblZKService.ForeColor = Color.Red;
                    SetLabel("  您的服务已存在，如服务异常，请点击“修复”！", this.lblZKService);
                }
            }

            Thread.Sleep(300);
            //检测杀毒软件
            tsslabState.Text = "检测杀毒软件...";
            LogHelper.SaveLog("检测杀毒软件进程开始...", "");
            List<AntiVirus> virusTmp = SystemInfo.GetKavass();

            List<AntiVirus> virus = new List<AntiVirus>();
            if (virusTmp.Count > 0)
            {
                virusTmp.ForEach(o =>
                {
                    if (!o.Equals(AntiVirus.MAC_FEE) && !o.Equals(AntiVirus.AVFWSVC))
                    {
                        virus.Add(o);
                    }
                });
            }

            if (virus.Count > 0)
            {
                tsslabState.Text = "安装前请关闭" + SystemInfo.GetViruNames(virus) + "软件后重新检测！";

                this.Invoke(new Action(() =>
                {
                    this.lblVirus.Show();
                    this.lblVirus.ForeColor = Color.Red;
                    SetLabel("× 杀毒软件或安全管家检测未通过，请先关闭" + SystemInfo.GetViruNames(virus) + "！", this.lblVirus);
                }));

                result = false;
            }
            else
            {
                this.Invoke(new Action(() =>
                {
                    this.lblVirus.Show();
                    this.lblVirus.ForeColor = Color.Black;
                    SetLabel("√ 杀毒软件检测通过。", this.lblVirus);
                }));
            }
            Thread.Sleep(300);
            //----------------------------
            //检测操作系统
            tsslabState.Text = "检测操作系统...";
            SysConstant.OSVer = SystemInfo.GetOSVersion();
            if (SysConstant.OSVer.Equals(OsVer.UNKNOW))
            {
                tsslabState.Text = "您的操作系统是：" + EnumHelper.GetDescription(SysConstant.OSVer) + ",操作系统不支持！";

                this.Invoke(new Action(() =>
                {
                    this.lblOS.Show();
                    this.lblOS.ForeColor = Color.Red;
                    SetLabel("√ 操作系统检测未通过。", this.lblVirus);
                }));
                result = false;
            }
            else
            {
                this.Invoke(new Action(() =>
                {
                    this.lblOS.Show();
                    String osInfo = "√ 操作系统检测通过，当前操作系统为：" + EnumHelper.GetDescription(SysConstant.OSVer) + "。";
                    this.lblOS.ForeColor = Color.Black;
                    if (SysConstant.OSVer.Equals(OsVer.WINXP1) || SysConstant.OSVer.Equals(OsVer.WINXP2))
                    {
                        result = false;
                        this.lblOS.ForeColor = Color.Red;
                        osInfo = "× 操作系统检测未通过，当前操作系统为：" + EnumHelper.GetDescription(SysConstant.OSVer) + "，请升级您的操作系统到 Windows XP SP3或以上版本！";
                    }
                    SetLabel(osInfo, this.lblOS);
                }));
            }
            Thread.Sleep(300);
            if (result)
            {
                tsslabState.Text = "√ 安装环境检测完毕";

                bool isInstallFirefox = false;//

                //xp 系统安装 firefox
                if (SysConstant.OSVer.Equals(OsVer.WINXP1) || SysConstant.OSVer.Equals(OsVer.WINXP2) || SysConstant.OSVer.Equals(OsVer.WINXP3))
                {
                    isInstallFirefox = Helper.ChkXpFirefoxInstall();
                    this.Invoke(new Action(() =>
                    {
                        if (!isInstallFirefox)
                        {
                            this.chkFirefox.Enabled = true;
                            this.chkFirefox.Checked = true;
                        }
                    }));
                }

                this.Invoke(new Action(() =>
                {
                    if (zhkServiceExists)
                    {
                        this.btnRepair.Enabled = true;
                        this.btnRepair.Focus();
                    }
                    else
                    {
                        this.btnAccept.Enabled = true;
                        this.btnAccept.Focus();
                    }
                }));
            }
            this.Invoke(new Action(() =>
            {
                this.btnReChk.Enabled = true;
            }));

            tsslabState.Image = null;
            tsslabState.Text = "检测完成！";
        }

        private void btnReChk_Click(object sender, EventArgs e)
        {
            this.lblVirus.Text = this.lblOS.Text = this.lblZKService.Text = "";

            Thread t = new Thread(new ThreadStart(() =>
            {
                try
                {
                    ChkEnv();
                }
                catch (Exception ex)
                {
                    LogHelper.SaveErrorLog("btnReChk_Click 异常", ex);
                }
            }));
            t.Start();
        }

        /// <summary>
        /// 修复
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRepair_Click(object sender, EventArgs e)
        {
            this.btnRepair.Enabled = false;

            DialogResult dr = MessageBox.Show("修复将重新安装 ZKOnlineProtectSvr 服务，确认操作？", "提示！", MessageBoxButtons.OKCancel);
            if (dr == DialogResult.OK)
            {
                Thread t = new Thread(new ThreadStart(() =>
                {
                    installService(true);
                }));
                t.Start();
            }
        }
    }
}
